﻿using Core.Domain.Entities;
using Finbuckle.MultiTenant;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Infrastructure.Persistence.Configurations;

public class UserProfileConfiguration : IEntityTypeConfiguration<UserProfile>
{
    public void Configure(EntityTypeBuilder<UserProfile> builder)
    {
        builder.ToTable("UserProfiles", SchemaNames.Identity)
            .IsMultiTenant();

        builder.HasKey(x => x.Id);

        builder.Property(x => x.UserId)
            .IsRequired(false);

        // ✅ 值对象集合配置（OwnsMany）
        builder.OwnsMany(x => x.Preferences, pref =>
        {
            pref.ToTable("UserPreferences", SchemaNames.Identity);

            // EF 自动创建外键列 UserProfileId（无 FK 约束）
            pref.WithOwner().HasForeignKey("UserProfileId");

            // ✅ 复合主键：UserProfileId + Key
            pref.HasKey("UserProfileId", "Key");

            pref.Property(x => x.Key)
                .HasMaxLength(100)
                .IsRequired();

            pref.Property(x => x.Value)
                .HasColumnType("nvarchar(max)")
                .IsRequired();

            pref.Property(x => x.ValueType)
                .HasMaxLength(200);

            pref.Property(x => x.Description)
                .HasMaxLength(500);
        });

        // ✅ 告诉 EF 使用私有字段存取集合
        builder.Navigation(x => x.Preferences)
            .Metadata.SetField("_preferences");
        builder.Navigation(x => x.Preferences)
            .UsePropertyAccessMode(PropertyAccessMode.Field);
    }
}
